import os
import zipfile
import pandas as pd

# import sys

destination_file_name = "uart_kis.log"
error_msg = "Error code: panic\(cpu 1 caller.+SEP Panic"

# logPath = os.path.join(os.path.split(__file__)[0], "log") # /Users/XXX/XXXX/XXX/tantan/src/log
# 所有压缩文件中的
all_uart_kis = {}
logPath = "src/log"  # /Users/XXX/XXXX/XXX/tantan/src/log
for zip_file in os.listdir(logPath):
    full_zip_file = os.path.join(logPath, zip_file)
    if zipfile.is_zipfile(full_zip_file):
        chapterfile = zipfile.ZipFile(full_zip_file)

        unzip_file_path = os.path.splitext(zip_file)[0]  # 解压后的文件夹
        sn = unzip_file_path.split("_")[0]
        # 如果解压后的文件已经存在的话就不要解压了
        if not os.path.isdir(unzip_file_path):
            # 不存在的话就要先解压
            chapterfile.extractall()

        all_uart_kis[sn] = [
            x
            for x in chapterfile.namelist()
            if os.path.split(x)[1] == destination_file_name
        ]

sn_arr = []
fail_msg_arr = []
for sn, file_names in all_uart_kis.items():
    for file_name in file_names:
        msg = "unknow"
        with open(file_name, "r") as f:
            line = f.readline()
            while line:
                # print(line.strip()) # 把末尾的'\n'删掉
                if error_msg in line.strip():
                    msg = error_msg
                    break
                line = f.readline()
        sn_arr.append(sn)
        fail_msg_arr.append(msg)


mydataset = {"SN": sn_arr, "Error code": fail_msg_arr}
df = pd.DataFrame(mydataset)
df.to_excel("foocsv.xlsx")
print(df)
